#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <memory>

enum
{
    USAGE_ERROR,
    SOCKET_ERROR,
    CONNECT_ERROR
};

void Usage(std::string proc)
{
    std::cout << "usage\n\t"
              << proc << "server_ip server_port" << std::endl;
}

enum class Status // C++11 强类型枚举
{
    NEW,          // 新建
    CONNECTING,   // 正在连接
    CONNECTED,    // 连接成功
    DISCONNECTED, // 连接失败
    CLOSED        // 重连失败，无法连接
};

class ClientConnection
{
public:
    ClientConnection(std::string ip, uint16_t port)
        : _sockfd(-1),
          _serverip(ip),
          _serverport(port),
          _retry_interval(1),
          _max_retries(5),
          _status(Status::NEW)
    {
    }

    void Connect()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(SOCKET_ERROR);
        }

        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        inet_pton(AF_INET, _serverip.c_str(), &server.sin_addr);
        // server.sin_addr.s_addr=inet_addr(_serverip.c_str());
        // p:process(进程), n(网络)

        int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            Disconnet();
            _status = Status::DISCONNECTED;
            return;
        }
        _status = Status::CONNECTED;
        std::cout << "connect success" << std::endl;
        return;
    }

    void Disconnet()
    {
        if (_sockfd != -1)
        {
            close(_sockfd);
            _sockfd = -1;
            _status = Status::CLOSED;
        }
    }

    void Reconnect()
    {
        _status = Status::CONNECTING;
        int cnt = 0;
        while (cnt < _max_retries)
        {
            Connect();
            if (_status == Status::CONNECTED)
                return;
            cnt++;
            std::cout << "重连中... " << cnt << "/" << _max_retries << std::endl;
            sleep(_retry_interval);
        }
        _status = Status::CLOSED;
        std::cout << "重连失败，请检查网络设置" << std::endl;
        exit(CONNECT_ERROR);
    }

    void Process()
    {
        while (true)
        {
            std::string message = "hello server";
            ssize_t n = send(_sockfd, message.c_str(), message.size(), 0);
            if (n > 0)
            {
                char buffer[1024];
                ssize_t m = recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
                if (m > 0)
                {
                    buffer[m] = 0;
                    std::cout << "server echo# " << buffer << std::endl;
                }
                else if (m == 0) // 服务器掉线
                {
                    _status = Status::DISCONNECTED;
                    break;
                }
                else
                {
                    _status = Status::CLOSED;
                    std::cerr << "recv error" << std::endl;
                    break;
                }
            }
            else
            {
                _status = Status::CLOSED;
                std::cerr << "send error" << std::endl;
                break;
            }
            sleep(1);
        }
    }

    Status GetStatus()
    {
        return _status;
    }

    ~ClientConnection()
    {
        Disconnet();
    }

private:
    int _sockfd;
    std::string _serverip;
    uint16_t _serverport;

    int _retry_interval; // 重连间隔时间
    int _max_retries;    // 最大重连次数
    Status _status;
};

class TcpClient
{
public:
    TcpClient(std::string serverip, uint16_t serverport)
        : _conn(serverip, serverport)
    {
    }
    void Excute()
    {
        while (true)
        {
            switch (_conn.GetStatus())
            {
            case Status::NEW:
                _conn.Connect();
                break;
            case Status::CONNECTED:
                _conn.Process();
                break;
            case Status::DISCONNECTED:
                _conn.Reconnect();
                break;
            case Status::CLOSED:
                _conn.Disconnet();
                break;
            default:
                // Do nothing
                break;
            }
        }
    }

private:
    ClientConnection _conn;
};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    std::unique_ptr<TcpClient> uclient = std::make_unique<TcpClient>(ip, port);
    uclient->Excute();

    return 0;
}
